package com.tencent.wxcloudrun.config;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.tencent.wxcloudrun.pojo.po.XCloudTable;
import com.tencent.wxcloudrun.pojo.po.XContractTemplate;
import com.tencent.wxcloudrun.service.XCloudTableService;
import com.tencent.wxcloudrun.service.XContractTemplateService;
import com.tencent.wxcloudrun.service.business.MapCloudService;
import com.tencent.wxcloudrun.util.PdfUtil;
import com.tencent.wxcloudrun.util.WinXinUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Component
@Slf4j
public class InitService implements CommandLineRunner {

    @Resource
    private MapCloudService mapCloudService;

    @Resource
    private XContractTemplateService xContractTemplateService;

    @Resource
    private XCloudTableService xCloudTableService;

    @Resource
    private WinXinUtils winXinUtils;

    @Resource
    private RedissonLockService redissonLockService;

    @Override
    public void run(String... args) throws Exception {
        boolean systemInitInfo = redissonLockService.lock("system_init_info", 1000, 120000);
        Date date = new Date();
        log.info("Spring Boot 应用已启动，正在执行自定义方法...");
        try {
            if (systemInitInfo) {
                log.info("尝试初始化【地图云table信息表】");
                dealMapInit(date);
                log.info("初始化合同模板信息，模板要放到对象存储中，不然前端不好预览");
                dealContractInit(date);
            }
        } finally {
            redissonLockService.unlock("system_init_info");
            log.info(">>>>>> 系统初始化完成，解开分布式锁。");
        }
    }

    private void dealContractInit(Date date) throws IOException {
        List<XContractTemplate> all = xContractTemplateService.list();
        if (CollUtil.isEmpty(all)) {
            return;
        }
        List<XContractTemplate> waitBe = all.stream().filter(var -> "0".equals(var.getBeFlag())).collect(Collectors.toList());
        for (XContractTemplate contractTemplate : waitBe) {
            String tmpId = "租房合同模板.pdf";
            String htmlContent = contractTemplate.getHtmlContent();
            String replace = htmlContent.replace("${contractNumber}", "XXXXXX")
                    .replace("${landlordName}", "张三")
                    .replace("${landlordId}", "42xxxxxxxxxxxxxxxx")
                    .replace("${landlordSex}", "男")
                    .replace("${landlordPhone}", "15xxxxxxxxx")
                    .replace("${tenantName}", "李四")
                    .replace("${tenantId}", "45xxxxxxxxxxxxxxxx")
                    .replace("${tenantSex}", "女")
                    .replace("${tenantPhone}", "17xxxxxxxxx")
                    .replace("${address}", "XX省XX市XX区XX街道XX路XX小区XX号")
                    .replace("${area}", "XX")
                    .replace("${houseNum}", "XXX")
                    .replace("${houseDesc}", "XXXXXXXXXX")
                    .replace("${startDate}", "XXXX年XX月XX日")
                    .replace("${endDate}", "XXXX年XX月XX日")
                    .replace("${rentAmount}", "XXXX")
                    .replace("${qianYueShijian}", "XXXX年XX月XX日")
                    .replace("${jiaoZuShijian}", "XXXX年XX月XX日")
                    .replace("${depositAmount}", "XXXX")
                    .replace("${waterPrice}", "XXX")
                    .replace("${waterNum}", "XXX")
                    .replace("${elePrice}", "XXX")
                    .replace("${eleNum}", "XXX")
                    .replace("${gasPrice}", "XXX")
                    .replace("${gasNum}", "XXX")
                    .replace("${managementFee}", "XXX")
                    .replace("${extraFeeDescription}", "XXXXXXXXXX")
                    .replace("${signJia}", "张三")
                    .replace("${signYi}", "李四");
            byte[] bytes = PdfUtil.html2Pdf(replace);
            String fileId = winXinUtils.uploadFile("contract/" + tmpId + ".pdf", bytes);
            XContractTemplate template = new XContractTemplate();
            template.setId(contractTemplate.getId());
            template.setTmpId(tmpId);
            template.setFileId(fileId);
            template.setBeFlag("1");
            template.setUpdateTime(date);
            xContractTemplateService.updateById(template);
        }
    }

    private void dealMapInit(Date date) {
        JSONObject jsonObject = mapCloudService.tableList();
        JSONArray tables = jsonObject.getJSONArray("tables");
        List<XCloudTable> all = xCloudTableService.list();
        if (CollUtil.isEmpty(all)) { // 还没有初始化过【地图云table信息表】
            for (Object table : tables) {
                JSONObject parseObject = JSON.parseObject(JSON.toJSONString(table));
                XCloudTable xCloudTable = new XCloudTable();
                xCloudTable.setTableId(parseObject.getString("table_id"));
                xCloudTable.setTableName(parseObject.getString("table_name"));
                xCloudTable.setDataCount(parseObject.getInteger("data_count"));
                xCloudTable.setCreateTime(date);
                xCloudTableService.save(xCloudTable);
            }
        } else { // 如果已经有值了，就检查是否有新增的，这张表只能增加，不能删除数据的。
            List<String> tableIdList = all.stream().map(XCloudTable::getTableId).collect(Collectors.toList());
            for (Object table : tables) {
                JSONObject parseObject = JSON.parseObject(JSON.toJSONString(table));
                String tableId = parseObject.getString("table_id");
                String tableName = parseObject.getString("table_name");
                Integer dataCount = parseObject.getInteger("data_count");
                if (!tableIdList.contains(tableId)) {
                    XCloudTable table1 = new XCloudTable();
                    table1.setTableId(tableId);
                    table1.setTableName(tableName);
                    table1.setDataCount(dataCount);
                    table1.setCreateTime(date);
                    xCloudTableService.save(table1);
                }
            }
        }
    }
}
